package com.neudu.ssrs_yyzxservice.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.ssrs_yyzxservice.common.JSONReturn;
import com.neudu.ssrs_yyzxservice.mapper.BedMapper;
import com.neudu.ssrs_yyzxservice.mapper.BeddetailsMapper;
import com.neudu.ssrs_yyzxservice.mapper.CustomerMapper;
import com.neudu.ssrs_yyzxservice.pojo.Bed;
import com.neudu.ssrs_yyzxservice.pojo.Beddetails;
import com.neudu.ssrs_yyzxservice.pojo.Customer;
import com.neudu.ssrs_yyzxservice.service.BeddetailsService;
import com.neudu.ssrs_yyzxservice.service.CustomerService;
import com.neudu.ssrs_yyzxservice.service.impl.BedTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BedManageController {

    @Autowired
    private JSONReturn jsonReturn;

    @Autowired
    private BeddetailsService beddetailsService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private BeddetailsMapper beddetailsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private BedTransferService bedTransferService;

    /**
     * 获取床位详情列表，支持分页和关键词搜索
     */
    @RequestMapping("get_bed_details")
    public String getBedDetails(@RequestBody Map<String, Object> requestBody) {
        Integer pageNum = (Integer) requestBody.get("pageNum");
        if (pageNum == null) {
            pageNum = 1;
        }
        Integer pageSize = (Integer) requestBody.get("pageSize");
        if (pageSize == null) {
            pageSize = 10;
        }
        String keyword = (String) requestBody.get("keyword");

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Beddetails> beds;
            if (keyword == null || keyword.trim().isEmpty()) {
                beds = beddetailsMapper.selectAll();
            } else {
                beds = beddetailsMapper.selectByKeyword(keyword);
            }
            PageInfo<Beddetails> pageInfo = new PageInfo<>(beds);
            Map<String, Object> result = new HashMap<>();
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 根据顾客 ID 获取床位详情
     */
    @RequestMapping("get_beddetails_by")
    public String getBedDetailsBy(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer id = (Integer) requestBody.get("id");
            if (id == null) {
                return jsonReturn.returnError("参数 id 不能为空");
            }
            Beddetails beddetails = beddetailsService.getById(id);
            System.out.println("获取到的床位详情信息: " + beddetails);
            if (beddetails == null) {
                return jsonReturn.returnError("未找到对应的床位详情信息");
            }

            return jsonReturn.returnSuccess(beddetails);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_beddetails_by_customer_id")
    public String getBedDetailsByCustomerId(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer customerId = (Integer) requestBody.get("customerId");
            if (customerId == null) {
                return jsonReturn.returnError("参数 customerId 不能为空");
            }
            List<Beddetails> beddetailsList = beddetailsMapper.selectByCustomerId(customerId);
            System.out.println("获取到的床位详情信息: " + beddetailsList);
            if (beddetailsList == null || beddetailsList.isEmpty()) {
                return jsonReturn.returnError("未找到对应的床位详情信息");
            }

            // 为每个 Beddetails 对象设置 bed 信息
            for (Beddetails beddetails : beddetailsList) {
                Integer bedId = beddetails.getBedId();
                Bed bed = bedMapper.selectBedById(bedId);
                beddetails.setBed(bed);
            }

            return jsonReturn.returnSuccess(beddetailsList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 新增床位详情
     */
    @PostMapping("add_bed_details")
    public String addBedDetails(@RequestBody Beddetails beddetails) {
        try {
            System.out.println("接收到的新增床位详情数据: " + beddetails);
            // 检查顾客是否已存在于 beddetails 表中
            List<Beddetails> existingBeds = beddetailsMapper.selectByCustomerId(beddetails.getCustomerId());
            if (existingBeds != null && !existingBeds.isEmpty()) {
                System.out.println("该顾客已存在床位信息，不能重复添加");
                return jsonReturn.returnError("该顾客已存在床位信息，不能重复添加");
            }
            boolean result = beddetailsService.save(beddetails);
            if (result) {
                System.out.println("新增床位详情成功: " + beddetails);
                return jsonReturn.returnSuccess("新增床位详情成功");
            } else {
                System.out.println("新增床位详情失败，可能是床位不可用或顾客已分配床位");
                return jsonReturn.returnError("新增床位详情失败，可能是床位不可用或顾客已分配床位");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("新增床位详情出现异常: " + e.getMessage());
            return jsonReturn.returnError("新增床位详情失败：" + e.getMessage());
        }
    }

    @PostMapping("update_bed_details")
    public String updateBedDetails(@RequestBody Beddetails beddetails) throws JsonProcessingException {
        // 新增校验：id 不能为空
        System.out.println("接收到的修改床位详情数据: " + beddetails);
        if (beddetails.getId() == null) {
            return jsonReturn.returnError("参数 id 不能为空");
        }
        try {
            Beddetails existingBeddetails = beddetailsService.getById(beddetails.getId());
            if (existingBeddetails == null) {
                return jsonReturn.returnError("未找到对应的床位详情信息，无法修改");
            }
            existingBeddetails.setStartDate(beddetails.getStartDate());
            existingBeddetails.setEndDate(beddetails.getEndDate());
            existingBeddetails.setBedDetails(beddetails.getBedDetails());
            beddetailsService.updateById(existingBeddetails);
            return jsonReturn.returnSuccess("修改床位详情成功");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("修改床位详情失败：" + e.getMessage());
        }
    }


    /**
     * 获取可用顾客列表（未在 beddetails 表中的顾客）
     */
    @PostMapping("get_available_customers")
    public String getAvailableCustomers() {
        try {
            List<Customer> customers = customerMapper.getAvailableCustomers();
            return jsonReturn.returnSuccess(customers);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取可用顾客列表失败：" + e.getMessage());
        }
    }

    // 新增：获取空闲床位列表（bed_status=1）
    @PostMapping("get_available_beds")
    public String getAvailableBeds() {
        try {
            List<Bed> beds = beddetailsMapper.selectAvailableBeds(); // 自定义SQL查询空闲床位
            return jsonReturn.returnSuccess(beds);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取可用床位失败：" + e.getMessage());
        }
    }


    @PostMapping("/bed_transfer")
    public Map<String, Object> transferBed(@RequestBody Map<String, Object> request) { // 改为 Map<String, Object>
        Integer bedDetailId = (Integer) request.get("bedDetailId");
        Integer newBedId = (Integer) request.get("newBedId");

        Map<String, Object> response = new HashMap<>();

        if (bedDetailId == null || newBedId == null) {
            response.put("success", false);
            response.put("message", "参数 bedDetailId 和 newBedId 不能为空");
            return response;
        }

        String result = bedTransferService.transferBed(bedDetailId, newBedId);
        if (result.equals("床位调换成功")) {
            response.put("success", true);
            response.put("message", result);
        } else {
            response.put("success", false);
            response.put("message", result);
        }

        return response;
    }
}